//
//  NewsViewController.m
//  B
//
//  Created by lanou on 16/5/7.
//  Copyright © 2016年 裴启航. All rights reserved.
//

#import "NewsViewController.h"
#import "NewsModel.h"
#import "NewsCell.h"
#import "TableViewCellFactory.h"
#import "UIView+QHExtension.h"
#import "ChannelCollectionViewCell.h"
#import "FootBallMatchModel.h"
#import "NewsDetailViewController.h"
#import "FootballDetailViewController.h"
#import "SpreadCollectionView.h"
#import "SVProgressHUD.h"
#import "BacketballListViewController.h"
#import "FootballMarchViewController.h"

// 体育新闻
#define kNewsUrl @"http://api.avatardata.cn/SportsNews/Query?key=79302edfc42e4459af9603a367b7e706"
// NBA赛事
#define KNBAMarchUrl @"http://api.avatardata.cn/Nba/NomalRace?key=dd766fcff49047919433fdb70f93e158"


@interface NewsViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    NSInteger pageNumber;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;

// collectionView

@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) NSMutableArray *newsArray;


// collectionView --> Array
@property (nonatomic, strong) NSArray *collectionArray;
// collectionView --> imageArray
@property (nonatomic, strong) NSArray *imageArray;
// 返回顶部的按钮
@property (nonatomic, strong) UIButton *backTopButton;
// rightButton
@property (nonatomic, strong) UIButton *rightButton;
// rightBarButtonItem
@property (nonatomic, strong) UIBarButtonItem *rightButtonItem;
@property (nonatomic, strong) SpreadCollectionView *spreadView;

@end

@implementation NewsViewController
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
}
- (void)viewWillDisappear:(BOOL)animated {
    [SVProgressHUD dismiss];
}
-(NSArray *)collectionArray
{
    if (!_collectionArray) {
        _collectionArray = [NSArray arrayWithObjects:@"英超", @"西甲", @"德甲", @"意甲", @"法甲", @"中超", nil];
    }
    return _collectionArray;
}
-(NSArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [NSArray arrayWithObjects:@"EPL_logo", @"LFP_logo", @"Bundesliga_logo", @"SERIE_logo", @"CFL_logo", @"CSL_logo", nil];
    }
    return _imageArray;
}
-(NSMutableArray *)newsArray
{
    if (!_newsArray) {
        _newsArray = [NSMutableArray array];
    }
    return _newsArray;
}
//-(UIButton *)rightButton
//{
//    if (!_rightButton) {
//        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        _rightButton.frame = CGRectMake(0, 0, 20, 20);
//        [_rightButton setImage:[UIImage imageNamed:@"list"] forState:UIControlStateNormal];
//        [_rightButton addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
//    }
//    return _rightButton;
//}
//-(UIBarButtonItem *)rightButtonItem
//{
//    if (!_rightButtonItem) {
//        _rightButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_rightButton];
//    }
//    return _rightButtonItem;
//}
-(UIButton *)backTopButton
{
    if (!_backTopButton) {
        _backTopButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _backTopButton.frame = CGRectMake(ScreenWidth - 20 - 30, ScreenHeight - 64 - 30, 30, 30);
        [_backTopButton addTarget:self action:@selector(backTopAction:) forControlEvents:UIControlEventTouchUpInside];
        _backTopButton.backgroundColor = [UIColor cyanColor];
        [_backTopButton setTitle:@"top" forState:UIControlStateNormal];
        _backTopButton.layer.cornerRadius = _backTopButton.frame.size.width / 2.0;
        _backTopButton.layer.masksToBounds = YES;
    }
    return _backTopButton;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    pageNumber = 0;
    self.view.backgroundColor = [UIColor cyanColor];
    // 数据请求
    [self getNewsData];
    // tableView
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 10000;
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass([NewsModel class])];
    [self.tableView registerNib:[UINib nibWithNibName:@"FootBallTableViewCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass([FootBallMatchModel class])];
//    self.tableView.tableHeaderView = view;
    [self.view addSubview:self.backTopButton];
    
    // 菊花
    [SVProgressHUD showWithStatus:@"waiting"];
    
    // 刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getNewsData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self getNewNewsData];
    }];
    UIBarButtonItem *football = [[UIBarButtonItem alloc] initWithTitle:@"足球比赛" style:(UIBarButtonItemStylePlain) target:self action:@selector(footer)];
    UIBarButtonItem *backetball = [[UIBarButtonItem alloc] initWithTitle:@"NBA" style:UIBarButtonItemStylePlain target:self action:@selector(backet)];
    self.navigationItem.rightBarButtonItems = @[football, backetball];
}
// 点击事件
- (void)footer {
    FootballMarchViewController *vc = [[FootballMarchViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];    
}

- (void)backet {
    BacketballListViewController *backetVC = [[BacketballListViewController alloc] init];
    [self.navigationController pushViewController:backetVC animated:YES];
}
#pragma mark - button返回
-(void)backTopAction:(UIButton *)button
{
    [self.tableView setContentOffset:CGPointMake(0, -64) animated:YES];
}
#pragma mark - 新闻数据请求
-(void)getNewsData
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    pageNumber++;
    [session GET:[kNewsUrl stringByAppendingFormat:@"&page=%@&rows=%@", [NSString stringWithFormat:@"%ld", (long)pageNumber], @"20"] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"%@", [kNewsUrl stringByAppendingFormat:@"&page=%@&rows=%@", [NSString stringWithFormat:@"%ld", (long)pageNumber], @"20"]);
        if (self.newsArray.count != 0) {
            [self.newsArray removeAllObjects];
        }
        NSArray *resultArr = responseObject[@"result"];
        for (NSDictionary *dict in resultArr) {
            [self.newsArray addObject:[NewsModel modelWithDic:dict]];
        }
        if (self.newsArray.count > 0) {
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
        // 菊花消失
        [SVProgressHUD dismiss];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}
// 上滑刷新
-(void)getNewNewsData
{
    pageNumber += 2;
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:[kNewsUrl stringByAppendingFormat:@"&page=%@&rows=%@", [NSString stringWithFormat:@"%ld", (long)pageNumber], @"20"] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", [kNewsUrl stringByAppendingFormat:@"&page=%@&rows=%@", [NSString stringWithFormat:@"%ld", (long)pageNumber], @"20"]);
        
        NSArray *resultArr = responseObject[@"result"];
        for (NSDictionary *dict in resultArr) {
            [self.newsArray addObject:[NewsModel modelWithDic:dict]];
        }
        if (self.newsArray.count > 0) {
            [self.tableView reloadData];
        }
        [self.tableView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}
#pragma mark - 足球比赛数据请求

#pragma mark - tableView - 代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_segment.selectedSegmentIndex == 0) {
        return 1;
    } else {
        return 2;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    if (self.segment.selectedSegmentIndex == 0) {
        return self.newsArray.count;
//    }
//    else if(self.segment.selectedSegmentIndex == 1) {
//        return self.footballArray.count;
//    } else {
//        return 0;
//    }
}
// 分区顶部视图
//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    if (_segment.selectedSegmentIndex == 0) {
//        return nil;
//    } else {
//        if (section == 0) {
//            NSString *zifuchuang = @" - 第一轮";
//           
//            // 球赛名称 - 结束
//            NSString *finishTeam = [_getCollectionTitle stringByAppendingString:zifuchuang];
//            
//            NSLog(@"%@", finishTeam);
//            
//            return finishTeam;
//        } else {
//            NSString *zifuchuang = @" - 第二轮";
//            NSString *str = [_getCollectionTitle stringByAppendingString:zifuchuang];
//            return str;
//        }
//    }
//}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsModel *newsModel = [[NewsModel alloc]init];
    if (self.segment.selectedSegmentIndex == 0) {
        newsModel = self.newsArray[indexPath.row];
        BaseTableViewCell *cell = [TableViewCellFactory cellWithModelClass:[newsModel class] tableView:tableView index:indexPath];
        [cell setDataWithModel:newsModel];
        return cell;
    } else {
        return nil;
        }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsModel *newsmodel = [[NewsModel alloc]init];
//    FootBallMatchModel *footballModel = [[FootBallMatchModel alloc]init];
    if (self.segment.selectedSegmentIndex == 0) {
        newsmodel = self.newsArray[indexPath.row];
        NewsDetailViewController *ndvc = [[NewsDetailViewController alloc]init];
        ndvc.getUrl = newsmodel.url;
        ndvc.model = newsmodel;
        
        int value = rand() % 20000 + 10086;
        
        ndvc.number = [NSString stringWithFormat:@"%ld", (long)indexPath.row + value];
        NSLog(@"%@", ndvc.number);
        
        [self.navigationController pushViewController:ndvc animated:YES];
    }
//    else {
//        FootballDetailViewController *fbVC = [[FootballDetailViewController alloc]init];
//        if (indexPath.section == 0) {
//            footballModel = self.footballArray[indexPath.row];
//            fbVC.getUrl1 = footballModel.c52Link;
//        } else {
//            footballModel = self.unStartFBArray[indexPath.row];
//            fbVC.getUrl1 = footballModel.c52Link;
//        }
//        [self.navigationController pushViewController:fbVC animated:YES];
//    }
}
#pragma mark - 滑动不显示，停止滑动显示
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_spreadView removeFromSuperview];
    self.rightButton.selected = NO;
    self.backTopButton.hidden = YES;
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    // 手动调用方法
    [self performSelector:@selector(scrollViewDidEndScrollingAnimation:) withObject:nil afterDelay:0.1];
}
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    self.backTopButton.hidden = NO;
    [self.tableView reloadData];
}
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (self.segment.selectedSegmentIndex == 0) {
        return nil;
    } else {
        return @[@"已结束", @"未开赛"];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}
- (void)dealloc {
    // 移除
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [SVProgressHUD dismiss];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
